package com.cysyz.mylib.myfilter.impl;

import com.cysyz.mylib.myfilter.MyFilter;
import com.cysyz.mylib.myfilter.matcher.Matcher;
import com.cysyz.mylib.utils.MyStringUtils;

import java.util.*;
import java.util.regex.Pattern;


public class PatternFilter extends  SimpleMyFilter implements MyFilter {
    private SimpleMyFilter simpleMyFilter;

    public PatternFilter(Collection<String> includes, Collection<String> excludes) {
        super(includes, excludes);

        final Map<String, Pattern> patternsMap =  new HashMap<>();

        initPatternMap(includes, excludes, patternsMap);

        this.simpleMyFilter = new SimpleMyFilter(new Matcher() {
            @Override
            public boolean match(Object target, Object includeOrExcludeVal) {
                Pattern pattern = patternsMap.get(includeOrExcludeVal);

                return pattern.matcher((CharSequence) target).matches();
            }
        }, includes, excludes);
    }

    private void initPatternMap(Collection<String> includes, Collection<String> excludes, Map<String, Pattern> patternsMap) {
        for (String include : includes) {
            patternsMap.put(include, Pattern.compile(include.trim()));
        }

        for (String exclude : excludes) {
            patternsMap.put(exclude, Pattern.compile(exclude.trim()));
        }
    }

    public PatternFilter(String includesCsv, String excludesCsv) {
        this(MyStringUtils.hasText(includesCsv) ? Arrays.asList(includesCsv.split(",")) : new ArrayList<String>(), MyStringUtils.hasText(excludesCsv) ? Arrays.asList(excludesCsv.split(",")) : new ArrayList<String>());
    }

    @Override
    public boolean filter(Object target) {
        return simpleMyFilter.filter(target);
    }
}
